//
//  NickViewController.swift
//  newShaohuoRen
//
//  Created by hujinbiao on 2018/3/24.
//  Copyright © 2018年 hujinbiao. All rights reserved.
//

import UIKit
import SwiftProgressHUD

protocol NickViewControllerDelegate {
    func nickViewController(nickName:String,realName:String)
}

class NickViewController: UITableViewController {
    
    @IBOutlet weak var nickTextField: UITextField!
    
    
    var delegate : NickViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        nickTextField.becomeFirstResponder()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "保存", style: .plain, target: self, action: #selector(saveBtnAction))

    }
    
    @objc func saveBtnAction() -> Void {
        
        if nickTextField.text!.isEmpty||nickTextField.text!.hasPrefix(" "){
            SwiftProgressHUD.showOnlyText("输入的内容不合法")
            return
        }
        if title=="昵称" {
            requestUpdateUserInfo(nick_name: nickTextField.text!, real_name: "")
        }else {

            requestUpdateUserInfo(nick_name: "", real_name: nickTextField.text!)
        }
    }
    
    func requestUpdateUserInfo(nick_name:String,real_name:String) -> Void {

        //要加密的数据
        let param = ["command":"updateUserInfo","uid":UserTicketModel.sharedInstance.uid ?? "","token":UserTicketModel.sharedInstance.token ?? "","nick_name":nick_name,"real_name":real_name,"app_name":"shr"]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"UserInfo"], successed: { (resultDict) in
            
            SwiftProgressHUD.showOnlyText("操作成功")
            let data = resultDict["data"] as! [String:AnyObject]
            let nickName = data["nick_name"] as! String
            let realName = data["real_name"] as! String
            self.delegate?.nickViewController(nickName: nickName, realName: realName)
            self.navigationController?.popViewController(animated: true)
        })
    }
}

extension NickViewController {
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.001
    }
}
